package com.organization

class ProjectService {

    def commonService

    def getProjectInfo(projId){
        Project proj = Project.get(commonService.nodeIdToDbId(projId))
        if (proj){
            def result = [name:proj.name, startDate:proj.startDate, dueDate:proj.dueDate, description: proj.description]
            result.putAll(commonService.goodResponse)
            return result
        }
        return commonService.badResponse
    }

    def updateProjectInfo(params){
        Project proj = Project.get(commonService.nodeIdToDbId(params.nodeId))
        if (proj){
            proj.name = params.name
            proj.startDate = commonService.convertDateFromJson(params.startDate)
            proj.dueDate = commonService.convertDateFromJson(params.dueDate)
            proj.description = params.description
            if (proj.validate()){
                proj.save()
                def response = [:]
                response.putAll(commonService.goodResponse)
                response.putAt('newName',params.name)
                response.putAt('nodeId',params.nodeId)
                return response
            }
            else {
                return commonService.parseErrorsFromDomain(proj.errors)
            }
        }
        return commonService.badResponse
    }

    def addProject(params){
        Department dep = Department.get(commonService.nodeIdToDbId(params.parentNodeId))
        if (dep){
            Project proj = new Project(
                    department: dep,
                    name: params.name,
                    startDate: commonService.convertDateFromJson(params.startDate),
                    dueDate: commonService.convertDateFromJson(params.dueDate),
                    description: params.description
            );
            if (proj.save()){
                proj.startDate = commonService.convertDateFromJson(params.startDate)
                proj.dueDate = commonService.convertDateFromJson(params.dueDate)
                def response = [:]
                response.putAll(commonService.goodResponse)
                response.putAt('nodeId',commonService.projNodeStr+proj.id.toString())
                response.putAt('parentNodeId',params.parentNodeId)
                return response
            }
            else {
                return commonService.parseErrorsFromDomain(proj.errors)
            }
        }
        return commonService.badResponse
    }

    def deleteProject(params){
        Project proj = Project.get(commonService.nodeIdToDbId(params.nodeId))
        if (proj){
            proj.delete()
            return commonService.goodResponse
        }
        return commonService.badResponse;
    }

}
